package wta.mongo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

public class AddPositiveExamDataToMongo {

	private static Mongo mongo;
	private static DB db;
	private static DBCollection coll;

	public static void main(String[] args) throws Exception {
		mongo = new Mongo("10.110.150.226");
		db = mongo.getDB("china");
		coll = db.getCollection("positive");
		
		File dic  = new File("D:\\百度云同步盘\\Now\\ciming\\数据\\4ciming11w\\11w01");
		String[] list = dic.list();
		
		for (String string : list) {
			insert(dic.getAbsolutePath() +'\\'+ string);
		}

		mongo.close();
	}
	
	public static void insert(String s) throws Exception {
		System.out.println("开始插入文件："+s);
		BufferedReader br = new BufferedReader(new FileReader(s));

		BasicDBObject toModify = null, toFind = null;
		String curID = null;
		int count = 0;

		while (true) {
			String line = br.readLine();
			if (line == null){
				break;
			}
			String[] info = line.split("\\$");
			if (info.length < 3)
				continue;
			toFind = new BasicDBObject();
			toFind.put("uid", info[0]);

			if (curID == null) {
				// 当最开始，或者用户id不同的时候，新建一个用户
//				System.out.println("新建用户：" + info[1]);
				toModify = new BasicDBObject();
				curID = info[0];
			} else if (!curID.equals(info[0])) {
				// 当用户变换的时候，新建一个用户，并插入modify
				toFind.clear();
				toFind.put("uid",curID);
				DBObject obj = coll.findOne(toFind);
				if (obj == null){
					//System.err.println(info[0] + " not found" + info[1]);
				}else {
					WriteResult re = coll.update(obj, new BasicDBObject(
							"$set", toModify), true, false);
				}

				toModify = new BasicDBObject();
				curID = info[0];
			}
			// 当用户id相同的时候，继续往里面put
			try{
				double value = Double.parseDouble(info[2]);
				toModify.put(info[1], value);
			}catch(NumberFormatException e){
				toModify.put(info[1], info[2]);
			}
			count++;
		}

		DBObject obj = coll.findOne(toFind);
		if (obj == null) {
		} else {
			WriteResult re = coll.update(obj, new BasicDBObject("$set",
					toModify), true, false);
		}

		System.out.println("done with " + count + "  " + s);
		System.out.println(System.currentTimeMillis() / 1000);
		br.close();
	}
}
